package com.cloudkinto.controller.orderoutput;


import com.cloudkinto.base.BaseController;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.extentity.order.LabellaOrderTrackNumberDto;
import com.cloudkinto.service.file.FileImportRecordService;
import com.cloudkinto.service.orderoutput.OrderOutputService;
import com.cloudkinto.service.orderoutput.importVo.OrderImportErrorVo1;
import com.cloudkinto.service.orderoutput.vo.*;
import com.cloudkinto.service.stock.StockRecordService;
import com.cloudkinto.service.stock.vo.record.StockRecordPageRes;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 张永远
 * @since 2020-06-04
 */
@RestController
@Api(tags = "出库订单模块")
@RequestMapping("/api/orderOutput")
public class OrderOutputController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(OrderOutputController.class);

    @Autowired
    private OrderOutputService service;
    @Autowired
    private StockRecordService stockRecordService;
    @Autowired
    private FileImportRecordService fileImportRecordService;

    @UserSessionRequired
    @GetMapping("/getFileImportRecord")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页大小"),
            @ApiImplicitParam(name = "shopId", value = "店铺id")
            , @ApiImplicitParam(name = "beginTime", value = "开始时间"), @ApiImplicitParam(name = "beginTime", value = "结束时间")})
    @ApiOperation(value = "获取上传记录", notes = "获取上传记录")
    public PageResult getFileImportRecord(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
//        String type = request.getParameter("type");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        String beginTime = request.getParameter("beginTime");
        String endTime = request.getParameter("endTime");
        String shopId = request.getParameter("shopId");
        map.put("companyId", getCompanyId()+"");
        map.put("type", "output");
        if (StringUtils.isNotBlank(beginTime)) {
            map.put("beginTime", beginTime);
        }
        if (StringUtils.isNotBlank(endTime)) {
            map.put("endTime", endTime);
        }
//        if (StringUtils.isNotBlank(type)) {
//            map.put("type", type);
//        }
        if (StringUtils.isNotBlank(shopId)) {
            map.put("shopId", shopId);
        }
        map.put("current", current);
        map.put("pageSize", size);
        return fileImportRecordService.getListPage(map);
    }

    @UserSessionRequired
    @GetMapping("/addInit")
    @ApiOperation(value = "新增初始化", notes = "新增初始化")
    public SingleResult addInit() {
        return service.addInit(getCurrentUserId(), getCompanyId());
    }

    @UserSessionRequired
    @PostMapping("add")
    @ApiOperation(value = "新增", notes = "新增")
    public SingleResult add(@RequestBody @Validated OrderOutputAddReq req) {
        Long userId = getCurrentUserId();
        if (req.getCompanyId() == null || req.getCompanyId() == 0) {
            req.setCompanyId(getCompanyId());
        }
        Long companyId = getCompanyId();
        req.setCompanyId(companyId);
        String value = service.add(req, userId);
        if (value == null) {
            return SingleResult.success("新增成功");
        } else {
            return SingleResult.failure(value);
        }
    }

    @UserSessionRequired
    @GetMapping("/updateInit/{id}")
    @ApiOperation(value = "编辑初始化", notes = "编辑初始化")
    @ApiResponses({@ApiResponse(code = 200, message = "", response = OrderOutputDetailRes.class)})
    public SingleResult<OrderOutputDetailRes> updateInit(@PathVariable("id") Long id) {
        return service.updateInit(id);
    }

    @UserSessionRequired
    @PutMapping("/update")
    @ApiOperation(value = "修改", notes = "修改")
    public SingleResult update(@RequestBody @Validated OrderOutputUpdateReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", service.update(req, userId));
    }

    @UserSessionRequired
    @PutMapping("/updateStock")
    @ApiOperation(value = "修改", notes = "修改")
    public SingleResult updateStock(@RequestBody @Validated OrderOutputUpdateReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("刷新库存成功", service.updateStock(req, userId));
    }

    @UserSessionRequired
    @PutMapping("/order/cutoff/{id}")
    @ApiOperation(value = "截单", notes = "截单")
    public SingleResult cutoff(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        service.cutoff(id, userId,companyId);
        return SingleResult.success(null);
    }

    @UserSessionRequired
    @GetMapping("/order/salesReturn/init/{id}")
    @ApiOperation(value = "退货初始化", notes = "退货初始化")
    public SingleResult salesReturnInit(@PathVariable("id") Long id) {
        return service.salesReturnInit(id);
    }

    @UserSessionRequired
    @PostMapping("/order/salesReturn")
    @ApiOperation(value = "退货", notes = "截单")
    public SingleResult salesReturn(@RequestBody OrderOutputSalesReturnReq req) {
        service.salesReturn(req,getCurrentUserId(),getCompanyId());
        return SingleResult.success(null);
    }


    @UserSessionRequired
    @PostMapping("/order/repeat")
    @ApiOperation(value = "重新发货", notes = "截单")
    public SingleResult orderRepeat(Long id) {

        return service.orderRepeat(id,getCurrentUserId(),getCompanyId());
    }


    @UserSessionRequired
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", service.delete(id, userId));
    }

    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查看详情", notes = "根据id查看详情")
    @ApiResponses({@ApiResponse(code = 200, message = "", response = OrderOutputDetailRes.class)})
    public SingleResult<OrderOutputDetailRes> detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功", service.detail(id));
    }

    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit(getCompanyId(), getCurrentUserId());
    }

    @UserSessionRequired
    @GetMapping("/list")
    @ApiOperation(value = "查询", notes = "查询")
    @ApiImplicitParams(@ApiImplicitParam(name = "keyword", value = "关键字（模糊查询）"))
    public SingleResult list(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        if (StringUtils.isNotBlank(keyword)) {
            map.put("keyword", keyword.trim());
        }
        return SingleResult.success("查询成功", service.getList(map));
    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "keyword", value = "关键字搜索"), @ApiImplicitParam(name = "keyword", value = "关键字搜索"),
            @ApiImplicitParam(name = "current", value = "当前页"), @ApiImplicitParam(name = "pagesize", value = "页大小"),
            @ApiImplicitParam(name = "status", value = "订单状态"),
            @ApiImplicitParam(name = "trackId", value = "快递公司"), @ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "shopId", value = "店铺id"), @ApiImplicitParam(name = "storageId", value = "仓库id")
            , @ApiImplicitParam(name = "startDate", value = "开始时间"), @ApiImplicitParam(name = "endDate", value = "结束时间")})
    @ApiResponses({@ApiResponse(code = 200, message = "", response = OrderOutputListRes.class)})
    public PageResult<OrderOutputListRes> listPage(String keyword, String current, String pageSize,String multi, String orderOutputNumber, String orderNo, String trackNumber, String commoditySku, String storageSku,
                                                   String telPhone, String receiverName, String orderNoLike, String trackNumberLike,
                                                   String status, String dateType, String startDate, String endDate, String trackId, String shopId, String storageId) {
        Long companyId = getCompanyId();
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isNotBlank(keyword)) {
//            map.put("keyword", keyword.trim());
        }
        if (StringUtils.isNotBlank(orderOutputNumber)) {
            map.put("orderOutputNumber", orderOutputNumber.trim());
        }
        if (StringUtils.isNotBlank(orderNoLike)) {
            map.put("orderNoLike", orderNoLike.trim());
        }
        if (StringUtils.isNotBlank(trackNumberLike)) {
            map.put("trackNumberLike", trackNumberLike.trim());
        }
        if (StringUtils.isNotBlank(orderNo)) {
            map.put("orderNo", orderNo.trim());
        }
        if (StringUtils.isNotBlank(trackNumber)) {
            map.put("trackNumber", trackNumber.trim());
        }
        if (StringUtils.isNotBlank(commoditySku)) {
            map.put("commoditySku", commoditySku.trim());
        }
        if (StringUtils.isNotBlank(storageSku)) {
            map.put("storageSku", storageSku.trim());
        }
        if (StringUtils.isNotBlank(telPhone)) {
            map.put("telPhone", telPhone.trim());
        }
        if (StringUtils.isNotBlank(receiverName)) {
            map.put("receiverName", receiverName.trim());
        }

        map.put("current", current);
        map.put("pageSize", pageSize);
        map.put("status", status);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("trackId", trackId);
        map.put("storageId", storageId);
        map.put("multi", multi);
        if (StringUtils.isNotBlank(dateType)) {
            map.put("dateType", dateType);
        }
//        map.put("orderType", "1");//一件代发
        if (!StringUtils.isEmpty(shopId)) {
            map.put("shopId", shopId);
        } else if (getShopId() != null) {
            map.put("shopId", getShopId() + "");
        }
        map.put("companyId", companyId + "");
        return service.getListPage(map);
    }

    @UserSessionRequired
    @PostMapping("/uploadExcel")
    @ApiOperation(value = "导入发货单Excel", notes = "导入发货单Excel")
//    @ApiImplicitParams({@ApiImplicitParam(name = "file",value = "导入文件"  ,paramType = "file"), @ApiImplicitParam(name = "shopId", value = "店铺id"), @ApiImplicitParam(name = "storageId", value = "仓库id")})
    public SingleResult uploadExcel(MultipartFile file,Long shopId, Integer storageId, Integer tempType) {
        Long userid = getCurrentUserId();
        Long companyId = getCompanyId();
        if (shopId==null)throw new BizExceptionI18(SysConstant.Order_Send_NoShop);

        return service.dealwithExcel(file, tempType == null ? 1 : tempType, shopId, storageId, userid, companyId);
    }


    @UserSessionRequired
    @PostMapping("/dealForLabella")
    @ApiOperation(value = "导入发货单Labella", notes = "导入发货单Labella")
    public SingleResult dealForLabella(@RequestBody @Validated List<OrderOutputExcelImportNew> excelNewImportList) {
//        Long userid = getCurrentUserId();
//        Long companyId = getCompanyId();
        List<OrderImportErrorVo1> errorVo1List = service.dealForLabella(excelNewImportList);
        return SingleResult.success(errorVo1List);
    }

    @UserSessionRequired
    @PostMapping("/labellaGetTrackNumber")
    @ApiOperation(value = "labella同步单号api", notes = "labella同步单号api")
    public SingleResult labellaGetTrackNumber(@RequestBody @Validated List<String> platformOrderNos) {
        List<LabellaOrderTrackNumberDto> errorVo1List = service.labellaGetTrackNumber(platformOrderNos);
        return SingleResult.success(errorVo1List);
    }


    @UserSessionRequired
    @PostMapping("exportExcel")
    @ApiOperation(value = "导出所有数据excel")
    public void exportAll(@RequestBody OrderOutputExcelReq req, HttpServletResponse response) throws Exception {
        Long companyId = getCompanyId();
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isNotBlank(req.getKeyword())) {
//            map.put("keyword", req.getKeyword().trim());
        }
        map.put("current", req.getCurrent());
        if (StringUtils.isNotBlank(req.getDateType())) {
            map.put("dateType", req.getDateType());
        }
        if (StringUtils.isNotBlank(req.getOrderOutputNumber())) {
            map.put("orderOutputNumber", req.getOrderOutputNumber().trim());
        }
        if (StringUtils.isNotBlank(req.getOrderNo())) {
            map.put("orderNo", req.getOrderNo().trim());
        }
        if (StringUtils.isNotBlank(req.getTrackNumber())) {
            map.put("trackNumber", req.getTrackNumber().trim());
        }
        if (StringUtils.isNotBlank(req.getCommoditySku())) {
            map.put("commoditySku", req.getCommoditySku().trim());
        }
        if (StringUtils.isNotBlank(req.getStorageSku())) {
            map.put("storageSku", req.getStorageSku().trim());
        }
        if (StringUtils.isNotBlank(req.getTelPhone())) {
            map.put("telPhone", req.getTelPhone().trim());
        }
        if (StringUtils.isNotBlank(req.getReceiverName())) {
            map.put("receiverName", req.getReceiverName().trim());
        }

        if (StringUtils.isNotBlank(req.getOrderNoLike())) {
            map.put("orderNoLike", req.getOrderNoLike().trim());
        }
        if (StringUtils.isNotBlank(req.getTrackNumberLike())) {
            map.put("trackNumberLike", req.getTrackNumberLike().trim());
        }
        map.put("pageSize", req.getPageSize());
        map.put("status", req.getStatus());
        map.put("startDate", req.getStartDate());
        map.put("endDate", req.getEndDate());
        map.put("trackId", req.getTrackId());
        map.put("storageId", req.getStorageId());
//        map.put("orderType", "1");//一件代发
        if (!StringUtils.isEmpty(req.getShopId())) {
            map.put("shopId", req.getShopId());
        } else if (getShopId() != null) {
            map.put("shopId", getShopId() + "");
        }
        map.put("companyId", companyId + "");
        service.exportExcel(map,req, response);
    }

    @UserSessionRequired
    @GetMapping("/stockRecordListPage")
    @ApiOperation(value = "仓库商品查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "keyword", value = "关键字搜索"),
            @ApiImplicitParam(name = "current", value = "当前页"), @ApiImplicitParam(name = "pageSize", value = "页大小"),
            @ApiImplicitParam(name = "storageId", value = "仓库id"), @ApiImplicitParam(name = "shopId", value = "店铺id")})
    @ApiResponses({@ApiResponse(code = 200, message = "", response = StockRecordPageRes.class)})
    public PageResult<StockRecordPageRes> stockRecordListPage(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String shopId = request.getParameter("shopId");
        String storageId = request.getParameter("storageId");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        String productType = request.getParameter("productType");


        if (StringUtils.isNotBlank(keyword)) {
            map.put("keyword", keyword.trim());
        }
        if (StringUtils.isNotBlank(productType)) {
            map.put("productType", productType.trim());
        }
        map.put("storageId", storageId);
        if (!StringUtils.isEmpty(shopId)) {
            map.put("shopId", shopId);
        } else if (getShopId() != null) {
            map.put("shopId", getShopId() + "");
        }
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        map.put("current", current);
        map.put("pageSize", size);
        return stockRecordService.getListPage(map);
    }

    @GetMapping("/exportShippingLabelPdfByOutputId")
    @ApiOperation(value = "根据一件代发订单id导出FD订单标签文件PDF", notes = "导出PDF")
    public void exportShippingLabelPdfByOutputId(Long[] ids, HttpServletResponse response) {
        service.exportShippingLabelPdfByOutputId(ids, response);
    }
}

